package xyz.junerver.testcaptureandrecord

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import xyz.junerver.testcaptureandrecord.capture.CaptureScreen
import xyz.junerver.testcaptureandrecord.network.WebSocketManager

import android.widget.Toast
import com.google.zxing.integration.android.IntentIntegrator
import com.google.zxing.integration.android.IntentResult
import xyz.junerver.testcaptureandrecord.record.RecordWithServerActivity

class MainActivity : AppCompatActivity() {
    // UI 组件
    lateinit var mIvPreview: ImageView   // 显示截图预览的 ImageView
    lateinit var mBtnStartCapture: Button // 启动截图功能的 Button
    lateinit var mBtnStopCapture: Button  // 停止截图功能的 Button
    lateinit var buttonScan: Button // 扫码的 Butoon
    lateinit var recordButton: Button // 录屏方案
    lateinit var captureScreen: CaptureScreen // CaptureScreen 实例，用于处理截图功能
    /**
     * websocket 连接
     */
    private lateinit var webSocketManager: WebSocketManager

    /**
     * 扫码连接websocket
     */
    private fun ScanLinkWebSocket(url: String) {
        webSocketManager = WebSocketManager.getInstance()
        webSocketManager.setUrl(url)
        webSocketManager.connect()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // 设置活动的布局

        // 初始化 UI 组件
        mIvPreview = findViewById(R.id.iv_preview)
        mBtnStartCapture = findViewById(R.id.btn_start_capture)
        mBtnStopCapture = findViewById(R.id.btn_stop_capture)

        // 设置 "开始截图" 按钮的点击事件
        mBtnStartCapture.setOnClickListener {
            // 启动虚拟显示器以开始截图
            captureScreen.startVirtual {
                // 截图回调函数
                LogUtils.d("收到截图回调 - $it")
                // 在 ImageView 中显示截图
                mIvPreview.setImageBitmap(it)
            }
        }

        // 设置 "停止截图" 按钮的点击事件
        mBtnStopCapture.setOnClickListener {
            // 停止截图
            captureScreen.stop()
            if(webSocketManager != null) {
                 // webSocketManager
                webSocketManager.sendMessage("stop")
            } else {
                Toast.makeText(this, "websocket未初始化", Toast.LENGTH_LONG).show()
            }
        }

        // 扫码处理
        buttonScan = findViewById(R.id.button_scan)
        buttonScan.setOnClickListener {
            // 打开扫码枪
            Log.e("KEY", "开启扫码枪")
            // 启动二维码扫描
            val integrator = IntentIntegrator(this)
            integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES)
            integrator.setPrompt("请扫描客户端二维码")
            integrator.setCameraId(0) // Use a specific camera of the device
            integrator.setBeepEnabled(true)
            integrator.setBarcodeImageEnabled(true)
            integrator.initiateScan()
        }

//        recordButton = findViewById<Button>(R.id.btn_jump_to_record_screen)
//        recordButton.setOnClickListener {
//            //录屏与显示都在一个activity中
//            // startActivity(Intent(this, RecordScreenActivity::class.java))
//            //录屏抽离到services中
//            startActivity(Intent(this, RecordWithServerActivity::class.java))
//        }

        // 申请录屏权限
        Utils.createPermission(this)
    }

    /**
     * 处理屏幕录制权限申请的结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // 检查请求码是否匹配并且用户授权成功
        if (requestCode == Utils.REQUEST_MEDIA_PROJECTION) {
            if (resultCode == Activity.RESULT_OK) {
                GlobalConfig.intent = data!!
                captureScreen = CaptureScreen.getInstance(this, GlobalConfig.intent)
            }
        }

        // 获取扫描结果
        val result: IntentResult? = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                Toast.makeText(this, "扫码取消", Toast.LENGTH_LONG).show()
            } else {
                // 连接成功
                if (result.contents.startsWith("ws://") || result.contents.startsWith("wss://")) {
                    // 授权成功，连接websock
                    ScanLinkWebSocket(result.contents)
                } else {
                    Toast.makeText(this, "无效的websocket连接", Toast.LENGTH_LONG).show()
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

}
